import 'dart:convert';
import 'dart:async';
import 'package:flutter/services.dart';
import 'package:myapp/page/timeout/timeout.dart';
import './tools/index.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:myapp/state/notifications.dart';
import 'package:webview_flutter/webview_flutter.dart';
import 'package:webview_flutter_android/webview_flutter_android.dart';
import 'package:webview_flutter_wkwebview/webview_flutter_wkwebview.dart';

class MyView extends StatefulWidget {
  final String port;
  final String ip;
  const MyView({super.key, required this.ip, required this.port});

  @override
  State<MyView> createState() => _MyViewState();
}

class _MyViewState extends State<MyView> {
  late final WebViewController controller;
  bool _loading = true;
  Timer? _timer;

  static const MethodChannel _channel = MethodChannel('pda_scan');

  void _startTimer() async {
    const duration = Duration(seconds: 5); 
      _timer = Timer.periodic(duration, (timer) {
      Navigator.pushReplacement(context, MaterialPageRoute(builder: (context) => const TimeOut()));
    });
  }

  void cancelTimer() {
    if (_timer != null) {
      _timer?.cancel();
      _timer = null;
    }
  }

  @override
  void initState() {
    super.initState();

    _startTimer();

    late final PlatformWebViewControllerCreationParams params;
    if (WebViewPlatform.instance is WebKitWebViewPlatform) {
      params = WebKitWebViewControllerCreationParams(
        allowsInlineMediaPlayback: true,
        mediaTypesRequiringUserAction: const <PlaybackMediaTypes>{},
      );
    } else {
      params = const PlatformWebViewControllerCreationParams();
    }

    controller = WebViewController.fromPlatformCreationParams(params)
      ..setJavaScriptMode(JavaScriptMode.unrestricted)
      ..setBackgroundColor(const Color(0x00000000))
      ..setNavigationDelegate(
        NavigationDelegate(
          onProgress: (int progress) {
            // 页面加载进度变化时会调用
            debugPrint('页面加载进度--->>>> $progress%');
          },
          onPageStarted: (String url) {
            debugPrint('onPageStarted------------------$url');
            setState(() {
              _loading = true;
            });
            // 页面开始加载时调用
            debugPrint('页面开始加载--->>>> $url');
          },
          onPageFinished: (String url) async {
            // 页面加载完成时调用
            setState(() {
              _loading = false;
            });
            cancelTimer();
            debugPrint('页面加载完成--->>>> $url');
          },
          onWebResourceError: (WebResourceError error) {
            debugPrint('页面加载错误--->>>> ${error.description}, ${error.errorType},  WebResourceErrorType---$WebResourceErrorType');
          },
          onNavigationRequest: (NavigationRequest request) {
            return NavigationDecision.navigate;
          },
        ),
      )
      // 消息通讯
      ..addJavaScriptChannel('AppSDK', onMessageReceived: (message) async {
        try{
          Map data = jsonDecode(message.message);
          handleWebMessage(data, controller, context);
        } catch (e){
          debugPrint('err---->>>> ${message.message}');
        }
      })
      ..loadRequest(Uri.parse('http://${widget.ip}:${widget.port}'));


    // ios
    if (controller.platform is WebKitWebViewController) {
      (controller.platform as WebKitWebViewController)
          .setAllowsBackForwardNavigationGestures(true);
    }

    // android
    if (controller.platform is AndroidWebViewController) {
      _listenForBroadcast();
    }

    context.read<NotificationsStore>().changeMessageFun((payload){
      runJavaScriptCustomEvent('notificationResponse', payload);
    });

  }

  void runJavaScriptCustomEvent(String active, String info) {
    controller.runJavaScript("window.dispatchEvent(new CustomEvent('$active', { detail: JSON.parse('$info') }))");
  }

  _listenForBroadcast() {
    _channel.setMethodCallHandler((call) async {
      if (call.method == 'scanCode') {
        final String barcode = call.arguments;
        String jsonString = jsonEncode(barcode);
        runJavaScriptCustomEvent('scanMessage', jsonString);
      }
    });
  }

  @override
  void dispose() {
    if (controller.platform is AndroidWebViewController) {
      _channel.setMethodCallHandler(null);
    }
    context.read<NotificationsStore>().changeMessageFun(null);
    controller.clearLocalStorage();
    super.dispose();
  }

  void _willInvoked<T>(bool didPop, T? result) async {

    bool canGoBack = await controller.canGoBack();
    if (canGoBack) {
      controller.goBack();
      return;
    }

    showAlert();
  }

  void showAlert() {
    showDialog(
      context: context,
      builder: (BuildContext context) {
        return AlertDialog(
          title: const Text('提示', style: TextStyle(fontSize: 20)),
          content: const Text('是否退出App!'),
          actions: [
            TextButton(
              child: const Text('确定'),
              onPressed: () {
                SystemChannels.platform.invokeMethod('SystemNavigator.pop');
              },
            ),
            TextButton(
              child: const Text('取消'),
              onPressed: () {
                Navigator.of(context).pop();
              },
            ),
          ],
        );
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    return PopScope(
        canPop: false,
        onPopInvokedWithResult: _willInvoked,
        child: Scaffold(
            body: SizedBox.expand(
              child: _loading ? _loadingView() : WebViewWidget(controller: controller),
            )
        )
    );
  }

  // 加载中的页面
  Widget _loadingView(){
    return Container(
      width: double.infinity,
      color: Colors.white,
      child: Center(
        child: Image.asset(
          'assets/images/lod.gif',
          width: 100,
          height: 100,
        )
      )
    );
  }
}

